<template>
  <div class="finance-overview">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card revenue">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.totalRevenue) }}</h3>
              <p>总收入</p>
              <span class="stat-change positive" v-if="stats.revenueGrowth">+{{ stats.revenueGrowth }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card profit">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.totalProfit) }}</h3>
              <p>净利润</p>
              <span class="stat-change positive" v-if="stats.profitGrowth">+{{ stats.profitGrowth }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card expense">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><CreditCard /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.totalExpense) }}</h3>
              <p>总支出</p>
              <span class="stat-change negative" v-if="stats.expenseGrowth">+{{ stats.expenseGrowth }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card margin">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="stat-details">
              <h3>{{ stats.profitMargin }}%</h3>
              <p>利润率</p>
              <span class="stat-change positive" v-if="stats.marginGrowth">+{{ stats.marginGrowth }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 收入趋势图 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>收入趋势</span>
              <el-button-group size="small">
                <el-button @click="changeChartPeriod('week')">近7天</el-button>
                <el-button @click="changeChartPeriod('month')" type="primary">近30天</el-button>
                <el-button @click="changeChartPeriod('year')">近一年</el-button>
              </el-button-group>
            </div>
          </template>
          <div ref="trendChart" style="height: 350px;"></div>
        </el-card>
      </el-col>
      <!-- 收入构成 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>收入构成</span>
          </template>
          <div ref="pieChart" style="height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 近期交易 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>近期交易</span>
              <el-button size="small" @click="viewAllTransactions">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentTransactions" stripe>
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.type === 'income' ? 'success' : 'danger'">
                  {{ row.type === 'income' ? '收入' : '支出' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="{ row }">
                <span :class="row.type === 'income' ? 'amount-income' : 'amount-expense'">
                  {{ row.type === 'income' ? '+' : '-' }}¥{{ formatMoney(row.amount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="100" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 财务快捷操作 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="quick-actions">
            <el-button type="primary" @click="quickAddIncome">
              <el-icon><Plus /></el-icon>
              添加收入
            </el-button>
            <el-button type="danger" @click="quickAddExpense">
              <el-icon><Minus /></el-icon>
              添加支出
            </el-button>
            <el-button type="success" @click="generateReport">
              <el-icon><Document /></el-icon>
              生成报表
            </el-button>
            <el-button type="warning" @click="exportData">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { 
  Money, TrendCharts, CreditCard, DataAnalysis, 
  Plus, Minus, Document, Download 
} from '@element-plus/icons-vue'
import { getFinanceOverview, getIncomeList, getExpenseList } from '@/api/wash_service'

export default {
  name: 'FinanceOverview',
  components: {
    Money, TrendCharts, CreditCard, DataAnalysis,
    Plus, Minus, Document, Download
  },
  setup() {
    const trendChart = ref()
    const pieChart = ref()

    const stats = reactive({
      totalRevenue: 0,
      totalProfit: 0,
      totalExpense: 0,
      profitMargin: 0
    })

    const recentTransactions = ref([])
    const loading = ref(false)

    let trendChartInstance = null
    let pieChartInstance = null

    const formatMoney = (amount) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(amount)
    }

    // 加载财务概览数据
    const loadFinanceData = async () => {
      loading.value = true
      try {
        const res = await getFinanceOverview()
        if (res && (res.code === 200 || res.data)) {
          const data = res.data || res
          Object.assign(stats, {
            totalRevenue: data.totalRevenue || 0,
            totalProfit: data.totalProfit || 0,
            totalExpense: data.totalExpense || 0,
            profitMargin: data.profitMargin || 0
          })
        }
      } catch (error) {
        console.error('获取财务数据失败:', error)
        ElMessage.warning('获取财务数据失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }

    // 加载近期交易记录
    const loadRecentTransactions = async () => {
      try {
        const [incomeRes, expenseRes] = await Promise.all([
          getIncomeList({ page: 1, size: 3 }),
          getExpenseList({ page: 1, size: 2 })
        ])
        
        const transactions = []
        
        // 处理收入数据
        if (incomeRes && (incomeRes.code === 200 || incomeRes.data)) {
          const incomeData = incomeRes.data || incomeRes
          const incomes = incomeData.content || incomeData.records || incomeData || []
          incomes.forEach(item => {
            transactions.push({
              date: item.date || item.createdAt || new Date().toISOString().split('T')[0],
              type: 'income',
              description: item.description || '收入',
              amount: item.amount || 0,
              category: item.category || '其他'
            })
          })
        }
        
        // 处理支出数据
        if (expenseRes && (expenseRes.code === 200 || expenseRes.data)) {
          const expenseData = expenseRes.data || expenseRes
          const expenses = expenseData.content || expenseData.records || expenseData || []
          expenses.forEach(item => {
            transactions.push({
              date: item.date || item.createdAt || new Date().toISOString().split('T')[0],
              type: 'expense',
              description: item.description || '支出',
              amount: item.amount || 0,
              category: item.category || '其他'
            })
          })
        }
        
        // 按日期排序
        recentTransactions.value = transactions.sort((a, b) => new Date(b.date) - new Date(a.date))
      } catch (error) {
        console.error('获取交易记录失败:', error)
        recentTransactions.value = []
      }
    }

    const initTrendChart = () => {
      if (!trendChart.value) return
      
      trendChartInstance = echarts.init(trendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['收入', '支出', '利润']
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '收入',
            type: 'line',
            data: new Array(12).fill(0), // 初始化为0，等待后端数据
            itemStyle: { color: '#67C23A' },
            areaStyle: { opacity: 0.3 },
            smooth: true
          },
          {
            name: '支出',
            type: 'line',
            data: new Array(12).fill(0), // 初始化为0，等待后端数据
            itemStyle: { color: '#F56C6C' },
            areaStyle: { opacity: 0.3 },
            smooth: true
          },
          {
            name: '利润',
            type: 'line',
            data: new Array(12).fill(0), // 初始化为0，等待后端数据
            itemStyle: { color: '#409EFF' },
            smooth: true
          }
        ]
      }
      
      trendChartInstance.setOption(option)
    }

    const initPieChart = () => {
      if (!pieChart.value) return
      
      pieChartInstance = echarts.init(pieChart.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '收入构成',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            data: [], // 初始化为空，等待后端数据
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      pieChartInstance.setOption(option)
    }

    const changeChartPeriod = (period) => {
      ElMessage.info(`切换到${period === 'week' ? '近7天' : period === 'month' ? '近30天' : '近一年'}视图`)
      // TODO: 重新加载对应时间段的图表数据
    }

    const viewAllTransactions = () => {
      ElMessage.info('跳转到交易明细页面')
    }

    const quickAddIncome = () => {
      ElMessage.info('快速添加收入')
    }

    const quickAddExpense = () => {
      ElMessage.info('快速添加支出')
    }

    const generateReport = () => {
      ElMessage.info('生成财务报表')
    }

    const exportData = () => {
      ElMessage.info('导出财务数据')
    }

    const resizeCharts = () => {
      if (trendChartInstance) trendChartInstance.resize()
      if (pieChartInstance) pieChartInstance.resize()
    }

    onMounted(async () => {
      await nextTick()
      loadFinanceData()
      loadRecentTransactions()
      initTrendChart()
      initPieChart()
      
      window.addEventListener('resize', resizeCharts)
    })

    return {
      trendChart,
      pieChart,
      stats,
      recentTransactions,
      loading,
      formatMoney,
      changeChartPeriod,
      viewAllTransactions,
      quickAddIncome,
      quickAddExpense,
      generateReport,
      exportData
    }
  }
}
</script>

<style scoped>
.finance-overview {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-card.revenue {
  border-left: 4px solid #67C23A;
}

.stat-card.profit {
  border-left: 4px solid #409EFF;
}

.stat-card.expense {
  border-left: 4px solid #F56C6C;
}

.stat-card.margin {
  border-left: 4px solid #E6A23C;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  font-size: 40px;
  margin-right: 20px;
  color: #909399;
}

.stat-details h3 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stat-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.stat-change {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.stat-change.positive {
  background-color: #f0f9ff;
  color: #67C23A;
}

.stat-change.negative {
  background-color: #fef0f0;
  color: #F56C6C;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-income {
  color: #67C23A;
  font-weight: bold;
}

.amount-expense {
  color: #F56C6C;
  font-weight: bold;
}

.quick-actions {
  display: flex;
  gap: 10px;
}

.quick-actions .el-button {
  flex: 1;
}
</style> 